<template>
  <div class="container">
    <el-card class="box-card">
      <div class="subjects-head">
        <div class="left">
          <el-form :inline="true" :model="formInline" class="demo-form-inline">
            <el-form-item label="学科名称">
              <el-input v-model="formInline.subjectName"></el-input>
            </el-form-item>
            <el-button @click="onClear">清除</el-button>
            <el-button type="primary" @click="onSearch">搜索</el-button>
          </el-form>
        </div>
        <div class="right">
          <el-button
            type="success"
            icon="el-icon-edit"
            @click="dialogFormVisible = true"
            >新增学科</el-button
          >
        </div>
      </div>
      <div class="subjects-middle">
        <i class="el-icon-info"></i>
        <span>数据一共{{ count }}条</span>
      </div>
      <div class="subjects-main">
        <el-table :data="tableData" stripe style="width: 100%">
          <el-table-column type="index" label="序号" >
          </el-table-column>
          <el-table-column prop="subjectName" label="学科名称" >
          </el-table-column>
          <el-table-column prop="username" label="创建者" >
          </el-table-column>
          <el-table-column prop="addDate" label="创建日期" width="200">
          </el-table-column>
          <el-table-column
            prop="isFrontDisplay"
            label="前台是否显示"
            width="110"
          >
            <template slot-scope="scope">
              {{ scope.row.isFrontDisplay === 1 ? "是" : "否" }}
            </template>
          </el-table-column>
          <el-table-column prop="twoLevelDirectory" label="二级目录" >
          </el-table-column>
          <el-table-column prop="tags" label="标签" >
          </el-table-column>
          <el-table-column prop="totals" label="题目数量" >
          </el-table-column>
          <el-table-column prop="operation" label="操作" width="270">
            <template slot-scope="scope">
              <el-button
                size="small"
                type="text"
                @click="
                  $router.push(
                    `directorys?id=${scope.row.id}&name=${scope.row.subjectName}`
                  )
                "
                >学科分类</el-button
              >
              <el-button
                size="small"
                type="text"
                @click="
                  $router.push(
                    `tags?id=${scope.row.id}&name=${scope.row.subjectName}`
                  )
                "
                >学科标签</el-button
              >
              <el-button size="small" type="text" @click="updateUser(scope.row)"
                >修改</el-button
              >
              <el-button size="small" type="text" @click="onDelete(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :page="formInline.page"
          :pagesize="formInline.pagesize"
          :total="count"
          :current-page="currentPage"
          layout="prev, pager, next, sizes, jumper"
        >
        </el-pagination>
        <!-- 添加对话框 -->
        <el-dialog title="新增学科" :visible.sync="dialogFormVisible">
          <el-form :model="form" :rules="rules">
            <el-form-item
              label="学科名称"
              :label-width="formLabelWidth"
              prop="name"
            >
              <el-input
                v-model="form.name"
                placeholder="请输入学科名称"
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="是否显示"
              :label-width="formLabelWidth"
              prop="isShow"
            >
              <el-switch
                v-model="value"
                active-color="#13ce66"
                inactive-color="#ff4949"
              >
              </el-switch>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="addData">确 定</el-button>
          </div>
        </el-dialog>
        <!-- 修改对话框 -->
        <el-dialog title="修改学科" :visible.sync="updateFormVisible">
          <el-form :model="editSubjectsFrom" :rules="editRules">
            <el-form-item
              label="学科名称"
              :label-width="formLabelWidth"
              prop="subjectName"
            >
              <el-input
                v-model="editSubjectsFrom.subjectName"
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <el-form-item label="是否显示" :label-width="formLabelWidth">
              <el-switch
                v-model="editSubjectsFrom.isFrontDisplay"
                active-color="#13ce66"
                inactive-color="#ff4949"
              >
              </el-switch>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="updateFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="UpdateData">确 定</el-button>
          </div>
        </el-dialog>
      </div>
    </el-card>
  </div>
</template>

<script>
import dayjs from 'dayjs'
import 'dayjs/locale/zh-cn'
import { list, remove, add, update } from '@/api/hmmm/subjects.js'
export default {
  name: 'Subject',
  data () {
    return {
      updateFormVisible: false, // 更新对话框
      userId: '',
      editSubjectsFrom: {
        subjectName: '',
        isFrontDisplay: ''
      },
      formInline: {
        subjectName: '',
        page: 1,
        pagesize: 10
      },
      tableData: [],
      count: 0,
      currentPage: 1,
      dialogFormVisible: false, // 添加对话框
      form: {
        name: ''
      },
      formLabelWidth: '120px',
      value: true,
      rules: {
        name: [
          { required: true, message: '请输入学科名称', trigger: 'blur' },
          { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' }
        ]
      },
      editRules: {
        subjectName: [
          { required: true, message: '请输入学科名称', trigger: 'blur' },
          { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.loadingList()
  },
  computed: {
    isFrontDisplay () {
      if (this.value) {
        return 1
      } else {
        return 0
      }
    }
  },
  methods: {
    onClear () {
      this.formInline.subjectName = ''
      this.loadingList()
    },
    async onSearch () {
      this.formInline.page = 1
      this.loadingList()
    },
    async loadingList () {
      try {
        const { data } = await list(this.formInline)
        data.items.forEach(item => {
          item.addDate = dayjs(item.addDate).format('YYYY-MM-DD hh:ss:mm')
        })
        this.tableData = data.items
        console.log(this.tableData)
        this.count = data.counts
      } catch (err) {
        this.message('数据获取失败')
      }
    },
    async addData () {
      if (this.form.name.length < 3 || this.form.name.length > 8) {
        return
      }
      this.dialogFormVisible = true
      try {
        const data = await add({
          subjectName: this.form.name,
          isFrontDisplay: this.isFrontDisplay
        })
        console.log(data)
        this.$message('新增学科成功')
        this.dialogFormVisible = false
        this.loadingList()
        this.form.name = ''
      } catch (err) {
        this.$message('新增学科失败!')
        console.log(err)
      }
    },
    async onDelete (row) {
      const config = await this.$confirm(
        '此操作将永久删除该学科, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
      if (config !== 'confirm') {
        return this.$message('您取消了删除操作!')
      }
      try {
        await remove(row)
        this.loadingList()
        this.$message('删除成功!')
      } catch (err) {
        console.log(err)
        this.$message('删除失败,请稍后再试!')
      }
    },
    updateUser (row) {
      this.updateFormVisible = true
      this.editSubjectsFrom.subjectName = row.subjectName
      if (row.isFrontDisplay === 1) {
        this.editSubjectsFrom.isFrontDisplay = true
      } else {
        this.editSubjectsFrom.isFrontDisplay = false
      }
      this.userId = row.id
    },
    async UpdateData () {
      if (this.editSubjectsFrom.isFrontDisplay === true) {
        this.editSubjectsFrom.isFrontDisplay = 1
      } else {
        this.editSubjectsFrom.isFrontDisplay = 0
      }
      try {
        await update({
          id: this.userId,
          subjectName: this.editSubjectsFrom.subjectName,
          isFrontDisplay: this.editSubjectsFrom.isFrontDisplay
        })
        this.$message('修改学科成功')
        this.updateFormVisible = false
        this.loadingList()
      } catch (err) {
        this.$message('修改学科失败')
      }
    },
    handleSizeChange (val) {
      console.log(`每页 ${val} 条`)
      this.formInline.pagesize = val
      this.loadingList()
    },
    handleCurrentChange (val) {
      console.log(`当前页: ${val}`)
      this.formInline.page = val
      this.loadingList()
    }
  }
}
</script>

<style scoped lang="less">
.container {
  padding: 10px;
  .subjects-head {
    display: flex;
    justify-content: space-between;
    .left {
      display: flex;
      align-items: center;
    }
  }
  .subjects-middle {
    margin-bottom: 20px;
    padding: 10px 20px;
    background-color: #f4f4f5;
    font-size: 12px;
    color: #909399;
    i {
      margin-right: 10px;
    }
  }
  .subjects-main {
    .el-pagination {
      float: right;
      margin: 20px 0;
    }
  }
}
</style>
